package com.sise.cn.api.common.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sise.cn.api.common.config.LoginConfig;
import com.sise.cn.api.common.impl.helper.LoginHelper;
import com.sise.cn.api.common.po.AdminPO;
import com.sise.cn.api.common.po.BaseUserPO;
import com.sise.cn.api.common.po.UserPO;
import com.sise.cn.api.common.service.LoginValidService;
import com.sise.cn.constant.RedisConstant;
import com.sise.cn.constant.TimeConstant;
import com.sise.cn.dao.base.BaseMapper;
import com.sise.cn.redis.cache.RedisUtil;
import com.sise.cn.utils.LoginAccountInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @ClassName LoginValidServiceImpl
 * @Description
 * @Author CCJ
 * @Date 2020/6/3 16:49
 **/
@Service
public class LoginValidServiceImpl implements LoginValidService {

    @Autowired
    private BaseMapper baseMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginConfig loginConfig;


    @Override
    public LoginAccountInfo handleLogin(BaseUserPO po, HttpServletRequest request) {
        LoginAccountInfo accountInfo = new LoginAccountInfo();
        String ip = LoginHelper.getRealIP(request);
        if (po instanceof AdminPO) {
            AdminPO table = (AdminPO) po;
            AdminPO adminPO = baseMapper.select(table, AdminPO.class);
            LoginHelper.validLogin(adminPO, ip, redisUtil, loginConfig.getFailCount(), po.getVerifyCode());
            setAccountInfo(accountInfo, adminPO);
        } else {
            UserPO table = (UserPO) po;
            UserPO userPO = baseMapper.select(table, UserPO.class);
            LoginHelper.validLogin(userPO, ip, redisUtil, loginConfig.getFailCount(), po.getVerifyCode());
            setAccountInfo(accountInfo, userPO);
        }
        String loginKey = RedisConstant.LOGIN_LOGIN_INFO.replace("{token}", accountInfo.getToken());
        redisUtil.set(loginKey, JSON.toJSONString(accountInfo), TimeConstant.ONE_WEEK_SEN);
        return accountInfo;
    }

    private static void setAccountInfo(LoginAccountInfo accountInfo, BaseUserPO basePO) {
        accountInfo.setUserId(basePO.getId());
        accountInfo.setAccountStatus(basePO.getStatus());
        accountInfo.setNickName(basePO.getUserName());
        accountInfo.setAvatar(basePO.getAvatar());
        accountInfo.setToken(UUID.randomUUID().toString());
    }


    @Override
    public String weChatLogin(String openId, JSONObject json) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserPO userPO) {
        baseMapper.insert(userPO);
    }
}
